<?php
namespace Admin\Logic;

use Common\Model\ManagerModel;

class ManagerLogic extends ManagerModel
{
	protected function _initialize()
	{
		parent::_initialize();
	}
	
	public function login($data = array())
	{
		$where = array(
				'manager_username' => $data['name'],
		);
		
		$manager = $this->where($where)->join('__ROLE__ ON role_id = manager_role_id')->find();
		
		if( empty($manager) )
		{
			$this->error = '用户名不存在';
			
			return false;
		}
		
		// 权限拼接：角色权限、附加权限
		$manager['manager_level_raw'] = sprintf('%s,%s',$manager['manager_role_raw'],$manager['role_raw']);
		$manager['manager_level_data'] = sprintf('%s,%s',$manager['manager_role_data'],$manager['role_data']);
		
		$manager['manager_level_raw'] = trim($manager['manager_level_raw'],',');
		$manager['manager_level_data'] = trim($manager['manager_level_data'],',');
		
		if( password_check($data['pass'], $manager['manager_userpass'],$manager['manager_usersalt']) === false )
		{
			$this->error = '密码有误';
			
			return false;
		}
		
		if( $manager['manager_state'] == '0' )
		{
			$this->error = '账户已锁定';
			
			return false;
		}
		
		$data = array(
				'id' => $manager['manager_id'],
				'last_ip' => get_client_ip(),
				'last_time' => get_time(),
		);
		
		if( $this->updateByPK($data) === false )
		{
			$this->error = '更新日志失败';
			
			return false;
		}
		
		psession('manager',$manager);
		
		return true;
	}
	
	public function getPage($where = array(),&$pageShow = null,$pageSize = 10,$parameter=array())
	{
		$totalRows = $this->where($where)->count();
		
		$order = 'manager_state DESC,manager_id DESC';
		
		$data = $this->where($where)->pagination($totalRows,$pageShow,$pageSize,$parameter)->order($order)->getItems();
		
		foreach ($data as $key => &$item)
		{
			$item['state'] = get_format_state($item['manager_state']);
			
			$item['role_name'] = get_format_default($item['manager_role_name'],true,'--');
			$item['usernick'] = get_format_default($item['manager_usernick'],true,'--');
			$item['username'] = get_format_default($item['manager_username'],true,'--');
			$item['last_ip'] = get_format_default($item['manager_last_ip'],true,'--');
			$item['last_time'] = get_format_date($item['manager_last_time']);
			$item['register_ip'] = get_format_default($item['manager_register_ip'],true,'--');
			$item['register_time'] = get_format_date($item['manager_register_time']);
			// 编辑账户
			$item['edit'] = get_format_url('edit', $item['manager_id']);
			// 删除账户
			$item['delete'] = get_format_url('delete', $item['manager_id']);
			// 附加权限
			$item['level'] = get_format_url('level', $item['manager_id']);
			// 重置密码
			$item['resetpassword'] = get_format_url('resetpassword', $item['manager_id']);
			// 修改密码
			$item['password'] = get_format_url('password', null);
		}
		
		return $data;
	}
	
	// 新增及更新
	public function updateManager($data = array())
	{
		$data = $this->create($data);
		
		if( $data === false )
		{
			return false;
		}
		
		if( array_key_exists($this->getPk(),$data) === false )
		{
			$data['manager_usersalt'] = generate_string(6);
			
			$data['manager_userpass'] = password($data['manager_userpass'],$data['manager_usersalt']);
			
			$data['manager_register_time'] = get_time();
			
			$data['manager_register_ip'] = get_client_ip();
		}
		else
		{
			// 防止登录用户名被误修改
			unset($data['manager_username']);
		}
		
		return $this->updateRecord($data);
	}
	
	public function getEdit($pk = 0)
	{
		$data = $this->getItem($pk);
		
		foreach ($data as $key => $item)
		{
			$data['state'] = get_format_state($data['manager_state']);
			$data['last_ip'] = get_format_default($data['manager_last_ip']);
			$data['register_ip'] = get_format_default($data['manager_register_ip']);
			$data['last_time'] = get_format_date($data['manager_last_time']);
			$data['register_time'] = get_format_date($data['manager_register_time']);
		}
		
		return $data;
	}
	
	// 重置密码、修改密码
	public function updatePassword($data = array(),$type = 'password')
	{
		$data = $this->create($data,$type);
		
		if( $data === false )
		{
			return false;
		}
		
		$data['manager_usersalt'] = generate_string(6);
		
		$data['manager_userpass'] = password($data['manager_userpass'],$data['manager_usersalt']);
		
		return $this->updateRecord($data);
	}
	
	// 附加权限更新
	public function updateLevel($data = array())
	{
		$data['role_data'] = trim(implode(array_values($data['role_raw']), ','),',');
		
		$data['role_raw'] = trim(implode(array_keys($data['role_raw']), ','),',');
		
		return $this->updateByPK($data);
	}
	
	/**
	 * 这个算法有点绕，自己慢慢看
	 * @param unknown $level
	 * @param unknown $role
	 * @param unknown $manager
	 * @return unknown
	 */
	public function getListLevelByRoleAndManager($level = array(),$role = array(),$manager = array())
	{
		$role = explode(',', $role['role_raw']);
		
		$manager = explode(',', $manager['manager_role_raw']);
		
		foreach ($level as $keys => &$items)
		{
			foreach ($items['level'] as $key => &$item)
			{
				$item['disabled'] = false;
				
				$item['level_default'] = false;
				
				if( in_array($item['level_id'], $role) )
				{
					$item['disabled'] = true;
					
					$item['level_default'] = true;
				}
				
				if( in_array($item['level_id'], $manager) )
				{
					$item['level_default'] = true;
				}
			}
		}
		
		return $level;
	}
	
	public function updateByPK($data = array(),$options = array(),$replace = false)
	{
		$data = $this->create($data);
		
		return $this->updateRecord($data,$options,$replace);
	}
	
	public function getListByParm($where = array(),$order = '')
	{
		$data = $this->where($where)->order($order)->select();
		
		return $data;
	}
	
	public function deleteByPK($pk = 0)
	{
		return $this->deleteRecord($pk);
	}
}